package net.nanbean.nplayer;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.VideoView;

public class NplayerActivity extends Activity {
    /** Called when the activity is first created. */
	private static final String TAG = "Nplayer";

	private static final int SUBTITLE_1ST_ID = Menu.FIRST;
	private static final int SUBTITLE_2ND_ID = Menu.FIRST+1;
	private static final int SUBTITLE_NO_ID = Menu.FIRST+2;
	private static final int SUBTITLE_LARGE_ID = Menu.FIRST+3;
	private static final int SUBTITLE_NORMAL_ID = Menu.FIRST+4;
	private static final int SUBTITLE_SMALL_ID = Menu.FIRST+5;
		
	private VideoView mVideoView;
	private TextView mTitleView;
	private TextView mBatteryView;
	private TextView mCurrentTimeView;
	private TextView mElapsedTimeView;
	private ImageView mPlayImageView;
	private ImageView mPrevImageView;
	private ImageView mNextImageView;
	public WebView mSubTitleView;
	private SeekBar mTimeline;
	private View mTopPanel;
	private Boolean isPanelVisible=true;
	
	private SamiParser samiSubtitle;
	
	private Uri videoURI;
	
	private long mLastActionTime=0L;
	
	private int mPrevPostion = 0;
	
	private SharedPreferences mPreferences;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mPreferences = getSharedPreferences("NPlayerPref", Activity.MODE_PRIVATE);
        
        videoURI = getIntent().getData();
        
        Log.i(TAG, "URI :" + videoURI.toString());
    }
	
    @Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		
        mVideoView = (VideoView) findViewById(R.id.video_view);
        mTitleView = (TextView) findViewById(R.id.title);
        mBatteryView = (TextView) findViewById(R.id.battery);
        mCurrentTimeView = (TextView) findViewById(R.id.currenttime);
        mElapsedTimeView = (TextView) findViewById(R.id.elapsedtime);
        mPlayImageView = (ImageView) findViewById(R.id.playbutton);
        mPrevImageView = (ImageView) findViewById(R.id.prevbutton);
        mNextImageView = (ImageView) findViewById(R.id.nextbutton);
        mSubTitleView = (WebView) findViewById(R.id.subtitle);
        mTimeline = (SeekBar) findViewById(R.id.timeline);
        mTopPanel=findViewById(R.id.top_panel);
        
        mVideoView.setVideoURI(videoURI);
        
        clearPanels(true);
        
        mVideoView.setOnPreparedListener(new OnPreparedListener() {
			
			@Override
			public void onPrepared(MediaPlayer arg0) {
				// TODO Auto-generated method stub
		        mTitleView.setText(videoURI.getPath());
		        
		        mVideoView.postDelayed(onStartTime, 0);
		        
			}
		});
        
        BroadcastReceiver batteryReceiver = new BroadcastReceiver(){
            int scale = -1;
            int level = -1;
            
			@Override
			public void onReceive(Context con, Intent intent) {
				// TODO Auto-generated method stub
                level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
                scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
                Log.e(TAG, "battery % is " + level*100/scale + "%");
                
                mBatteryView.setText(level*100/scale + "%");
                
			}
        };
        
        IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(batteryReceiver, filter);
        
        addAllListener();

	}
    
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		
    	SharedPreferences.Editor editor = mPreferences.edit();
    	editor.putInt(videoURI.toString(), mPrevPostion );
    	editor.putInt(videoURI.toString() + "duration", mVideoView.getDuration() );
    	editor.commit();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		//menu.add(0, SUBTITLE_SELECT_ID, 1, R.string.select_subtitle);
		//menu.add(0, SUBTITLE_OPTION_ID, 1, R.string.subtitle_option);
		SubMenu subtitleSelectMenu = menu.addSubMenu(R.string.select_subtitle);
		SubMenu subtitleOptionMenu = menu.addSubMenu(R.string.subtitle_option);
		subtitleSelectMenu.add(0, SUBTITLE_1ST_ID, 0, R.string.subtitle_1st);
		subtitleSelectMenu.add(0, SUBTITLE_2ND_ID, 0, R.string.subtitle_2nd);
		subtitleSelectMenu.add(0, SUBTITLE_NO_ID, 0, R.string.subtitle_no);

		subtitleOptionMenu.add(0, SUBTITLE_LARGE_ID, 0, R.string.subtitle_large);
		subtitleOptionMenu.add(0, SUBTITLE_NORMAL_ID, 0, R.string.subtitle_normal);
		subtitleOptionMenu.add(0, SUBTITLE_SMALL_ID, 0, R.string.subtitle_small);
		
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
    	switch (item.getItemId()) {
			case SUBTITLE_1ST_ID:
				samiSubtitle.setSubtitleLanguage(1);
				samiSubtitle.showSubtitle(true);
				return true;
			case SUBTITLE_2ND_ID:
				samiSubtitle.setSubtitleLanguage(2);
				samiSubtitle.showSubtitle(true);
				return true;
			case SUBTITLE_NO_ID:
				samiSubtitle.showSubtitle(false);
				return true;
			case SUBTITLE_LARGE_ID:
				samiSubtitle.setSubtitleSize(25);
				return true;
			case SUBTITLE_NORMAL_ID:
				samiSubtitle.setSubtitleSize(20);
				return true;
			case SUBTITLE_SMALL_ID:
				samiSubtitle.setSubtitleSize(15);
				return true;
			default:
				return(super.onOptionsItemSelected(item));
				
		}
	}

	public void play() {
		int prevTime = 0;
		
		prevTime = mPreferences.getInt(videoURI.toString(), 0);
		
		mVideoView.seekTo(prevTime);
		
		mVideoView.start();
		
		samiSubtitle = new SamiParser(videoURI, mVideoView, mSubTitleView);
		
		samiSubtitle.showSubtitle(true);
		
	}
	
	public void pause() {
		mVideoView.pause();
	}
	
	public boolean isPlaying() {
		return mVideoView.isPlaying();
	}
	
    private void clearPanels(boolean both) {
    	mTopPanel.setVisibility(View.GONE);
    	
    	mTimeline.setVisibility(View.GONE);
    	mElapsedTimeView.setVisibility(View.GONE);
    	mPlayImageView.setVisibility(View.GONE);
    	mPrevImageView.setVisibility(View.GONE);
    	mNextImageView.setVisibility(View.GONE);
    	isPanelVisible = false;
    }
    
    private void showPanels(boolean both) {
    	mTopPanel.setVisibility(View.VISIBLE);

    	mTimeline.setVisibility(View.VISIBLE);
    	mElapsedTimeView.setVisibility(View.VISIBLE);
    	mPlayImageView.setVisibility(View.VISIBLE);
    	mPrevImageView.setVisibility(View.VISIBLE);
    	mNextImageView.setVisibility(View.VISIBLE);
    	isPanelVisible = true;
    }
	
	private void addAllListener() {
		
		mVideoView.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
	    		if(event.getAction() == MotionEvent.ACTION_DOWN)
	    		{
	    			mLastActionTime=SystemClock.elapsedRealtime();
	    			
	    			if(isPanelVisible)
		    			clearPanels(true);
		    		else
		    			showPanels(true);
						
	    			Log.d(TAG, "mVideoTouchEvent");
	    			
					return true;
	    		}

	    		Log.d(TAG, "onTouch : " + event.getAction());
	    		
				return false;
			}
		});
		
        mPlayImageView.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(isPlaying()) {
					pause();
					mPlayImageView.setImageDrawable(getResources().getDrawable(R.drawable.pause));
				}else {
					play();
					mPlayImageView.setImageDrawable(getResources().getDrawable(R.drawable.play));
				}
					
			}
        	
        });
        
        mNextImageView.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(isPlaying()) {
	    			int pos = mVideoView.getCurrentPosition();
	    			pos += 10000;
	    			
	    			Log.v(TAG, "current : " + mVideoView.getCurrentPosition() + "pos : " + pos);
	    			
	   				mVideoView.seekTo(pos);
				}else {

				}
					
				mLastActionTime=SystemClock.elapsedRealtime();
			}
        	
        });
        
        mPrevImageView.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(isPlaying()) {
	    			int pos = mVideoView.getCurrentPosition();
	    			pos -= 10000;
	    			
	    			Log.v(TAG, "current : " + mVideoView.getCurrentPosition() + "pos : " + pos);
	    			
	   				mVideoView.seekTo(pos);
				}else {

				}
					
				mLastActionTime=SystemClock.elapsedRealtime();
			}
        	
        });
        
        mTimeline.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			
			@Override
			public void onStopTrackingTouch(SeekBar arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onStartTrackingTouch(SeekBar arg0) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				// TODO Auto-generated method stub
	    		if(fromUser)
	    		{
		    		mVideoView.seekTo(progress);
		    		Log.v(TAG, "onProgressChanged : " + progress);
		    		
		        	mLastActionTime=SystemClock.elapsedRealtime();
	    		}
			}
		});
        
        mVideoView.setOnCompletionListener(new OnCompletionListener() {

			@Override
			public void onCompletion(MediaPlayer mp) {
				// TODO Auto-generated method stub
				finish();
			}
        	
        });
	}
	
    private Runnable onStartTime=new Runnable() {
    	public void run() {
    		
    		mTimeline.setMax(mVideoView.getDuration());
    		
    		Log.v(TAG, "timeline max : " + mVideoView.getDuration());
    		
//    		prevTime = mPreferences.getInt(path, 0);
    		
//    		Log.v(TAG, "prevTime : " + prevTime);
    		
//    		if(!playFromStart)
//    			mVideoView.seekTo(prevTime);
    		
    		play();
    		
	        mVideoView.postDelayed(onEvery500ms, 0);
//	        mVideoView.postDelayed(onSubtitleDisplay, SUBTITLE_INT);
    	}
    };
    
    private Runnable onEvery500ms=new Runnable() {
    	public void run() {

    		if (mLastActionTime>0 && (SystemClock.elapsedRealtime()-mLastActionTime)>2000)
    		{
    			clearPanels(false);
    		}
    		
    		int curPos = mVideoView.getCurrentPosition();
    		
    		if(mVideoView.isPlaying())
    		{
	    		Log.v(TAG, "curPos : " + curPos);
	    		mPrevPostion = curPos;
    		}
    		mTimeline.setProgress(curPos);
    		float totalsec = curPos / 1000;
    		float min = totalsec / 60;
    		float sec = totalsec % 60;
    		String elapsedTimeString = String.format("%02d:%02d", (int)min, (int)sec);
    		mElapsedTimeView.setText(elapsedTimeString);
    		
    		Time curTime = new Time();
    		curTime.set(System.currentTimeMillis());
    		
    		mCurrentTimeView.setText(curTime.hour+":"+curTime.minute);
    		
//            Log.v(TAG, "timeline progress : " + mVideoView.getCurrentPosition());
            
    		if(mVideoView.isPlaying())
    		{
    			mVideoView.postDelayed(onEvery500ms, 1000);
    		}
    	}
    };
}